import store from '..';

const state = {
  token: '',
};
const mutations = {
  setToken(state, token) {
    state.token = token;
  },
};
const actions = {
  async wxLogin(store) {
    const [errProfile, resProfile] = await uni.getUserProfile({ desc: '为' });
    const [errLogin, resLogin] = await uni.login();
    if (!errProfile && !errLogin) {
      const { encryptedData, rawData, iv, signature } = resProfile;
      const { code } = resLogin;
      const res = await uni.$u.post('/users/wxlogin', {
        encryptedData,
        rawData,
        iv,
        signature,
        code,
      });
      const { token } = res.message;
      store.commit('setToken', token);
    } else {
      uni.showToast({
        title: '登录失败，支付取消。需重新登录',
        icon: 'none',
      });
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
